package cn.xetsoft.supermarket.view;


import cn.xetsoft.supermarket.SupermarketApplication;
import cn.xetsoft.supermarket.common.DataResponse;
import cn.xetsoft.supermarket.service.Bean;
import cn.xetsoft.supermarket.service.SettingService;
import cn.xetsoft.supermarket.util.DbConfig;
import cn.xetsoft.supermarket.util.GUITools;
import cn.xetsoft.supermarket.util.PropertiesUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


/**
 * 系统管理页面
 */
public class SystemManagement extends JFrame {
    private JLabel state_label = new JLabel("正常");//状态标签标题
    private SupermarketApplication.CallResult result = new SupermarketApplication.CallResult();

    JLayeredPane layeredPane = new JLayeredPane();  // 面板层
    JButton button_storage = new JButton("存储");// 确认按钮
    JButton button_test = new JButton("连接测试");// 连接测试按钮
    JButton button_Init = new JButton("初始化数据库");// 初始化按钮
    JButton button_drop = new JButton("清库");//清库按钮
    JButton button_export = new JButton("导出数据(_)");//清库按钮
    JTextField text_ip   = new JTextField(24);//服务器IP和端口号
    JTextField text_name = new JTextField(24);          // 登陆用户名
    JTextField DBname = new JTextField(24);          // 登陆用户名
    JPasswordField text_password = new JPasswordField();    // 登陆密码

    //背景图
    private JLayeredPane layeredPaneBottom;
    private ImageIcon image;
    private JPanel jp;
    private JLabel jl;
    private SettingService settingService = Bean.getSettingServiceInstance();
    private boolean keyFlag = false;



    private static final long serialVersionUID = 1L;
    // 用于处理拖动事件，表示鼠标按下时的坐标，相对于JFrame
    int xOld = 0;
    int yOld = 0;

    class LoginOKAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
        }

    }

    class RegisterAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            setVisible(false);
            new RegisterFrame();
        }

    }

    class LoginCanselAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {

            System.exit(0);

        }

    }


    public SystemManagement() {
        super();
        this.setTitle("系统配置 - 熵客云超市管理");
        this.setSize(1300, 700);// 窗体大小与位置
        GUITools.center(this);//设置窗口在屏幕上的位置
        this.setResizable(false);// 窗体大小固定
        text_ip.setText(PropertiesUtil.getProperty("db.host"));
        text_name.setText(PropertiesUtil.getProperty("db.username"));
        text_password.setText(PropertiesUtil.getProperty("db.password"));
        DBname.setText(PropertiesUtil.getProperty("db.dbname"));
        initialize();
    }

    public SupermarketApplication.CallResult getResult() {
        return result;
    }

    public void setResult(SupermarketApplication.CallResult result) {
        this.result = result;
    }

    //重写方法
    @Override
    protected void processWindowEvent(WindowEvent e) {
        if (e.getID() == WindowEvent.WINDOW_CLOSING){
            boolean flag = settingService.initSystem().isSuccess();
            System.out.println(flag);
            if (flag) {
                result.setFlag(true);
                this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(null, "配置没有完成,请配置后关闭窗口");
                return;
            }
        }
    }

    //添加事件
    public void initialize() {
        this.setLayout(null);
        this.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e) {
//                System.out.println("触发windowClosing事件");


            }
        });
        // 处理拖动事件
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                xOld = e.getX();
                yOld = e.getY();
            }
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                int xOnScreen = e.getXOnScreen();
                int yOnScreen = e.getYOnScreen();

                int xx = xOnScreen - xOld;
                int yy = yOnScreen - yOld;
                SystemManagement.this.setLocation(xx, yy);
            }
        });

        //按钮导出事件点击监听器
        button_export.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (keyFlag){
                    new ImportDataFrame().setVisible(true);
                }else {
                    new ExportDataFrame().setVisible(true);
                }
            }
        });
        button_storage.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DbConfig dbConfig = new DbConfig();
                dbConfig.setUsername(text_name.getText());
                dbConfig.setDatabase(DBname.getText());
                dbConfig.setPassword(new String(text_password.getPassword()));
                dbConfig.setAddress(text_ip.getText());
                DataResponse dataResponse = settingService.initDbConfig(dbConfig); //调用初始化数据库服务
                if (dataResponse.isSuccess()){
                    JOptionPane.showMessageDialog(null,"存储成功！");
                }else {
                    JOptionPane.showMessageDialog(null,"存储失败！");
                }

            }
        });
        button_test.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DataResponse dataResponse = settingService.initSystem(); //调用初始化服务进行测试连接
                System.out.println(dataResponse);
                if (dataResponse.getCode() == 555){
                    JOptionPane.showMessageDialog(null,dataResponse.getMsg());
                } else if (dataResponse.getCode() == 4041 || dataResponse.getCode() ==4042){
                    int isSelect =JOptionPane.showConfirmDialog(null,dataResponse.getMsg()+" 是否初始化！","错误",JOptionPane.YES_NO_OPTION);
                    if (isSelect == JOptionPane.YES_OPTION){
                        settingService.initDatabase(false);
                    } else {
                        System.exit(4041);
                    }
                } else if (dataResponse.isSuccess()){
                    JOptionPane.showMessageDialog(null,dataResponse.getMsg());
                }else {
                    JOptionPane.showMessageDialog(null, dataResponse.getMsg());
                }
            }
        });
        button_Init.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectCode = JOptionPane.showConfirmDialog(null,"确认现在要初始化数据吗?这可能会导致现有数据被覆盖!","数据安全警告",JOptionPane.YES_NO_OPTION);
                if (selectCode == JOptionPane.YES_OPTION){
                    settingService.initDatabase(false);
                }
            }
        });
        button_drop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectCode = JOptionPane.showConfirmDialog(null,"确认现在要初始化数据吗?这可能会导致现有数据被覆盖!","数据安全警告",JOptionPane.YES_NO_OPTION);
                if (selectCode == JOptionPane.YES_OPTION){
                    String safecode = JOptionPane.showInputDialog("该操作会导致数据库清空,请输入'我确认删除数据库'以删除数据!");
                  if (safecode != null){
                      if (safecode.equalsIgnoreCase("我确认删除数据库")){
                          DataResponse dataResponse = settingService.initDatabase(true); //调用设置服务类进行清库
                          JOptionPane.showMessageDialog(null,dataResponse.getMsg() + ",数据库信息变更,请重启软件!");
                          System.exit(0); //清空数据库后程序退出
                      }else {
                          JOptionPane.showMessageDialog(null,"输入安全语错误,操作取消!");
                      }
                  }
                }else {
                    JOptionPane.showMessageDialog(null,"安全语输入错误或用户取消操作!");
                }
            }
        });

        button_export.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {

            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == 17){
                    button_export.setText("导入数据");
                    keyFlag = true;
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == 17){
                    button_export.setText("导出数据");
                    keyFlag = false;
                }
            }
        });

        //添加控件
        layeredPaneBottom=new JLayeredPane();
        /**
         * 得到路径区别开发环境和jar包
         */
        String imgFile = "Images/SystemManagement.png";
        if (!PropertiesUtil.getProperty("debug.resources.type").equals("jar")){
            imgFile = Class.class.getResource("/").getPath() + imgFile;
        }
        image=new ImageIcon(imgFile);//背景图片
        //创建背景
        jp=new JPanel();
        jp.setBounds(0,-10,image.getIconWidth(),image.getIconHeight());

        jl=new JLabel(image);
        jp.add(jl);

        //把控件在页面上进行定位
        text_ip.setBounds(687,150,380,44);
        text_name.setBounds(687,214,380,44);
        text_password.setBounds(687,278,380,44);
        DBname.setBounds(687,342,380,44);
        button_storage.setBounds(687,408,125,43);
        button_test.setBounds(849,408,186,43);
        button_export.setBounds(1072,408,125,43);
        button_Init.setBounds(537,509,127,43);
        button_drop.setBounds(688,509,124,43);
        state_label.setBounds(1120,508,124,43);
        state_label.setFont(new Font("alias", Font.PLAIN, 25));
        //将背景图放到最底层。
        layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER);
        //将按钮放到高一层的地方
        layeredPane.add(text_ip,JLayeredPane.MODAL_LAYER);
        layeredPane.add(text_name,JLayeredPane.MODAL_LAYER);
        layeredPane.add(text_password,JLayeredPane.MODAL_LAYER);
        layeredPane.add(DBname,JLayeredPane.MODAL_LAYER);
        layeredPane.add(button_storage,JLayeredPane.MODAL_LAYER);
        layeredPane.add(button_test,JLayeredPane.MODAL_LAYER);
        layeredPane.add(button_export,JLayeredPane.MODAL_LAYER);
        layeredPane.add(button_Init,JLayeredPane.MODAL_LAYER);
        layeredPane.add(button_drop,JLayeredPane.MODAL_LAYER);
        layeredPane.add(state_label,JLayeredPane.MODAL_LAYER);

        this.setLayeredPane(layeredPane);
        this.setSize(image.getIconWidth(),667);
        this.setVisible(true);
    }
}